<?php




namespace App\Services;


use App\Models\StoreOrderPayment;
use Illuminate\Support\Carbon;
use Illuminate\Support\Str;
use Yansongda\LaravelPay\Facades\Pay;

class Wechat
{


    /**
     * @param $open_id
     * @param $order_no
     * @param $price
     * @param string $title
     * @return \Yansongda\Supports\Collection
     */
    public function mini($open_id, $order_no, $price, $title = '微信订单')
    {

        $order = [
            'out_trade_no' => $order_no . '',
            'description' => $title,
            'amount' => [
                'total' => $price,
                'currency' => 'CNY',
            ],
            'payer' => [
                'openid' => $open_id,
            ]
        ];
        return Pay::wechat()->mini($order);
    }


    /**
     * @param $order_no
     * @param $price
     * @param string $title
     * @return \Yansongda\Supports\Collection
     */
    public function app($order_no, $price, $title = '微信充值')
    {
        $info = [
            'out_trade_no' => $order_no . '',
            'description' => $title,
            'amount' => [
                'total' => $price * 100,
            ],
        ];
        return Pay::wechat()->app($info);
    }


    /**
     * @param $order_no
     * @param $refund_no
     * @param $price
     * @param $total
     * @return array|\Psr\Http\Message\MessageInterface|\Yansongda\Supports\Collection|null
     * @throws \Yansongda\Pay\Exception\ContainerException
     * @throws \Yansongda\Pay\Exception\InvalidParamsException
     * @throws \Yansongda\Pay\Exception\ServiceNotFoundException
     */
    public function refund($order_no, $refund_no, $price, $total)
    {
        $order = [
            'out_trade_no' => $order_no,
            'out_refund_no' => $refund_no,
            'amount' => [
                'refund' => $price * 100,
                'total' => $total * 100,
                'currency' => 'CNY',
            ],
        ];
        return Pay::wechat()->refund($order);
    }

    /**
     * 数据回调
     * @return \Psr\Http\Message\ResponseInterface
     * @throws \Yansongda\Pay\Exception\ContainerException
     * @throws \Yansongda\Pay\Exception\InvalidParamsException
     */
    public function back()
    {
        $back = Pay::wechat()->callback();
        $result = $back['resource']['ciphertext'];

        if ($result['trade_state'] == 'SUCCESS') {
            $order_no = $result['out_trade_no'];
            $type = Str::limit($order_no, 1, '');
            $payResult['pay_no'] = $result['transaction_id'];
            $payResult['pay_time'] = Carbon::createFromTimestamp(strtotime($result['success_time']));
            $payResult['pay_price'] = $result['amount']['total'] / 100;
            $payResult['pay_type'] = 2;
            if ($type == 'M')
                (new StoreOrderPayment())->payMainOrder($order_no, $payResult);
        }
        return Pay::wechat()->success();
    }
}
